package src.tree.level_order;

import src.tree.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class no102 {//层序遍历

    public List<List<Integer>> levelOrder(TreeNode root) {

        ArrayList<List<Integer>> res = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();

        if (root == null) return res;
        queue.add(root);
        while (!queue.isEmpty()) {
            List<Integer> list = new ArrayList<>();
            int size = queue.size();
            //size表示当前层的元素个数，用来控制每个子数组装几个数
            while (size-- > 0) {
                TreeNode node = queue.poll();
                list.add(node.val);
                //每当一个node出队列时，就将它的左右孩子入队列
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);
            }
            res.add(list);
        }
        return res;

    }

}
